angular.module('app.directives', [])
    .directive('gsSiderMenu', function() {
        return {
            restrict: 'EA',
            template: '<li ng-repeat="item in menus | orderBy:Orderid" ng-class="{\'start\':$first,\'active open\':$currentMenu.indexOf(item.Url)>-1}"> ' +
                '<a href="javascript:;" ng-click="menuClick(item)"> ' +
                '<i class="{{item.template.icon}}"></i> ' +
                '<span class="title" ng-bind="item.Powername"></span> ' +
                '<span class="arrow" ng-if="item.submenu" ng-class="{\'open\':$currentMenu.indexOf(item.Url)>-1}"></span></a> ' +
                '<ul class="sub-menu animated" ng-if="item.submenu" ng-class="{\'fade-in-up\':$currentMenu.indexOf(item.Url)>-1}"> ' +
                '<gs-sider-menu menus="item.submenu"></gs-sider-menu> ' +
                '</ul></li>',
            scope: {
                menus: "="
            },
            replace: true,
            link: function(scope, elem, attrs) {
                // console.log(scope.menus);
            }
        };
    })
    .directive('picPreView', function($timeout) {
        return {
            restrict: 'EA',
            template: '<div class="imgPreview"><div class="close" ng-click="close()">&times;</div>' +
                '    <div class="img" ng-if=\'data.ftype==0\'><img id="imageView" ng-src="{{data.mediaUrl}}"/></div>' +
                "    <div class=\'showvideo\' ng-if=\'data.ftype==1\'>" +
                "        <video id='videoview' controls=\'controls\' ng-src=\'{{data.mediaUrl}}\'></video>" +
                "    </div>" +
                '</div>',
            scope: {
                url: "=",
                ftype: "=",
                close: "&"
            },
            link: function(scope, element, attrs) {
                var url = scope.url;
                var ftype = scope.ftype;
                if (!ftype && url) {
                    var ext = url.substr(url.lastIndexOf(".")).toLowerCase();
                    if (".png;.jpg;.jpeg;.gif;.bmp".indexOf(ext) != -1) {
                        ftype = 0;
                    } else if (".mp4;.ogg".indexOf(ext) != -1) {
                        ftype = 1;
                    } else {
                        ftype = -1;
                    }
                }
                console.log(ftype, url);
                scope.data = {
                    mediaUrl: url,
                    ftype: ftype,
                }
                if (ftype == 1) {
                    $timeout(function() {
                        var video = document.getElementById("videoview");
                        video.oncanplay = function() {
                            var vh = $("#videoview").height();
                            var bh = $("body").height();
                            var vw = $("#videoview").width();
                            var bw = $("body").width();
                            if (vh > bh) {
                                $("#videoview").height(bh + "px");
                            }
                            if (vw > bw) {
                                $("#videoview").width(bw + "px");
                            }
                        };
                    });
                } else if (ftype == 0) {
                    $timeout(function() {
                        var img = document.getElementById("imageView");
                        img.onload = function(data) {
                            var vh = $("#imageView").height();
                            var bh = $("body").height();
                            var vw = $("#imageView").width();
                            var bw = $("body").width();
                            if (vh > bh) {
                                $("#imageView").height(bh + "px");
                            }
                            if (vw > bw) {
                                $("#imageView").width(bw + "px");
                            }
                        };
                    });
                }
            }
        };
    })
    .directive('ngSpinnerBar', ['$rootScope',
        function($rootScope) {
            return {
                link: function(scope, element, attrs) {
                    // by defult hide the spinner bar
                    //element.addClass('hide'); // hide spinner bar by default

                    // display the spinner bar whenever the route changes(the content part started loading)
                    $rootScope.$on('$stateChangeStart', function() {
                        element.removeClass('hide'); // show spinner bar
                    });

                    // hide the spinner bar on rounte change success(after the content loaded)
                    $rootScope.$on('$stateChangeSuccess', function() {
                        element.addClass('hide'); // hide spinner bar
                        $('body').removeClass('page-on-load'); // remove page loading indicator

                        // auto scorll to page top
                    });

                    // handle errors
                    $rootScope.$on('$stateNotFound', function() {
                        element.addClass('hide'); // hide spinner bar
                    });

                    // handle errors
                    $rootScope.$on('$stateChangeError', function() {
                        element.addClass('hide'); // hide spinner bar
                    });
                }
            };
        }
    ])
    .directive('a', function() {
        return {
            restrict: 'E',
            link: function(scope, elem, attrs) {
                if (attrs.ngClick || attrs.href === '' || attrs.href === '#') {
                    elem.on('click', function(e) {
                        e.preventDefault(); // prevent link click for above criteria
                    });
                }
            }
        };
    })
    .directive('dropdownMenuHover', function() {
        return {
            link: function(scope, elem) {
                elem.dropdownHover();
            }
        };
    })
    .directive('gsInput', function($compile, $timeout, Tools, GgcmsOptions, dataApi, localStorageService) {
        return {
            restrict: "EA",
            templateUrl: sysConfigs.cfg_prefixpath + '/static/admin/template/tpl/forminput.html?rnd=' + Tools.timeStamp(),
            scope: {
                gsItem: "=",
                gsDependent: "=",
            },
            replace: true,
            link: function(scope, element, attrs) {
                scope.GgcmsOptions = GgcmsOptions;
                var opt = scope.gsItem.opts;
                var val = scope.gsItem.Value;
                if (['datetime', 'date'].indexOf(opt.type) != -1) {
                    scope.datePickerOptions = angular.copy(GgcmsOptions.datePicker);
                    if (opt.minDate) {
                        scope.datePickerOptions.minDate = new Date(Tools.dateExpress(opt.minDate, val));
                    }
                    if (opt.maxDate) {
                        scope.datePickerOptions.maxDate = new Date(Tools.dateExpress(opt.maxDate, val));
                    }
                }
                if (['select', 'checkbox', "radio"].indexOf(opt.type) != -1 && opt.datasource == "sysenum" && "" != opt.egroup) {
                    dataApi.inputDictInit(opt, scope);
                }
                //风格
                if (opt.type == 'select' && (opt.datasource == "style" || opt.datasource == "template")) {
                    if (!scope["style"]) {
                        var style = localStorageService.get("ggcms_cacth_style");
                        if (!style) {
                            var getStyleAll = dataApi.getStyleAll();
                            getStyleAll.then(function(data) {
                                console.log(data);
                                scope.style = data.Data;
                                localStorageService.update("ggcms_cacth_style", data.Data);
                            });
                        } else {
                            scope.style = style;
                        }
                    }
                }

                //模板过滤
                scope.templateFilter = function(name, val) {
                    var reg = eval("/" + val + "_/i");
                    return reg.test(name);
                };
                //checkbox多选框
                if (opt.type == "checkbox") {
                    scope.cbxItems = val.split(",");
                }
                scope.cbxchange = function(kv, ev) {
                    var idx = scope.cbxItems.indexOf(kv)
                    if (idx != -1) {
                        scope.cbxItems.splice(idx, 1);
                    } else {
                        scope.cbxItems.push(kv);
                    }
                    scope.gsItem.Value = scope.cbxItems.join(",");
                }
            },
        }
    })
    .directive('gsValidation', function($compile, $timeout, Tools, appHandle) {
        return {
            restrict: "EA",
            link: function(scope, element, attrs) {
                //console.log(scope.gsItem);
                var forid = scope.gsItem.Varname;
                //取数据是设置还是模型
                var opt = scope.gsItem.opts;
                var val = scope.gsItem.Value;

                $timeout(function() {
                    var ele = angular.element("#" + forid);
                    if (opt.required) {
                        attrs.$set('required', true);
                    }
                    if (opt.min > 0) {
                        attrs.$set('min', opt.min);
                    }
                    if (opt.max > 0) {
                        attrs.$set('max', opt.max);
                    }
                    if (opt.minLength > 0) {
                        attrs.$set('minlength', opt.minLength);
                    }
                    if (opt.maxLength > 0) {
                        attrs.$set('maxlength', opt.maxLength);
                    }
                    if (opt.pattern != "") {
                        attrs.$set('pattern', opt.pattern);
                    }

                    if (opt.type == "file") {
                        ele.attr('ngf-select', "upload($file,gsItem.Varname,true)");
                        if (opt.fileSize > 0) {
                            ele.attr('ngf-max-size', opt.fileSize + "kb");
                        }
                        if (opt.extension != "") {
                            ele.attr('ngf-pattern', opt.extension);
                        }
                    }

                    $compile(element[0])(scope);
                    //更新界面
                    if (opt.type == "switch") {
                        $("#" + forid).bootstrapSwitch();
                    }
                    appHandle.initComponents();
                });
                element.removeAttr("gs-validation");
            }
        }
    });